package com.service;

import com.dao.UserDao;
import com.entity.UserEntity;
import com.entity.UserGroupEntity;
import com.ex.MyException;
import top.appx.easysql.Restrain;
import top.appx.easysql.data.PageInfo;
import top.appx.espring.annotation.Autowired;
import top.appx.espring.annotation.Source;
import top.appx.espring.vo.QueryPageVO;
import top.appx.espring.vo.ResultVO;
import top.appx.zutil.DateTime;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Source
public class UserService {
    @Autowired
    private UserDao userDao;

    public UserEntity login(String username, String password){
        UserEntity user = userDao.queryByUsername(username);
        if(user == null){
            throw new MyException("用户名不存在或已被删除");
        }
        if(!user.getPassword().equals(password)){
            throw new MyException("密码错误");
        }
        userDao.updateLastTime(user.getId());
        return user;
    }
    public ResultVO queryPage(QueryPageVO queryPageVO){
        queryPageVO.getRestrainList().add(Restrain.eq("status","normal"));
        PageInfo pageInfo = userDao.queryPageVO(queryPageVO);
        return ResultVO.data().p("total",pageInfo.getTotal()).p("rows",pageInfo.getData());
    }

    public void add(UserEntity userEntity) {
        userEntity.setStatus("normal");
        userEntity.setCreateTime(DateTime.now());
        userDao.add(userEntity,"该用户名已存在",Restrain.eq("username",userEntity.getUsername()),Restrain.eq("del",1));
    }

    public void modify(UserEntity user) {
        userDao.modify(user,"已存在相同名称的用户名",Restrain.eq("username",user.getUsername()),Restrain.eq("del",1));
    }

    public void delById(int id){
        UserEntity user =new UserEntity();
        user.setId(id);
        user.setStatus("del");
        userDao.modify(user);
    }
    public int delByIds(List<Integer> ids) {
        UserEntity user = new UserEntity();
        user.setStatus("del");
        return userDao.modifys(user,Restrain.in("id",ids.toArray()));
    }

    public void resetPasswordByIds(List<Integer> ids, String newPassword) {
        UserEntity user = new UserEntity();
        user.setPassword(newPassword);
        userDao.modifys(user,Restrain.in("id", ids.toArray()));
    }


    public void modifyPassword(String username, String oldPassword, String newPassword) {
        UserEntity ue = userDao.queryByUsername(username);
        if(ue == null){
            throw new MyException("用户不存在或已删除");
        }

        if(!oldPassword.equals(ue.getPassword())){
            throw new MyException("密码错误");
        }

        UserEntity newUser = new UserEntity();
        newUser.setId(ue.getId());
        newUser.setPassword(newPassword);
        userDao.modify(newUser);
    }


}
